package com.focus.xyz.other.pages.pingan;

import com.focus.xyz.core.common.keyword.Action;
import com.focus.xyz.core.pages.BasePage;
import com.focus.xyz.core.utils.Constants;
import com.focus.xyz.core.utils.prop.ConfigPropInfo;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Created by chenmeng on 2016/6/29.
 */
public class OrderPage extends BasePage {
    private Action action;
    private WebDriver driver;
    private static final String searchResultUrl = "https://icorepnbs.pingan.com.cn/icore_pnbs/bussiness/quotationAndApply/templates/view/popup/quickSearch_result.html";
    @FindBy(xpath = "//input[@placeholder='车牌号']")
    private WebElement cardNo;
    @FindBy(xpath = "//button[contains(text(),'检索')]")
    private WebElement searchBtn;


    /*
    * 客户信息检索
    * */
    @FindBy(xpath = "//input[@ng-model='personnelInfo.personnelName']")
    private WebElement custName;
    @FindBy(xpath = "//select[@ng-model='personnelInfo.certificateTypeCode']")
    private WebElement cardType;
    @FindBy(xpath = "//input[@ng-model='personnelInfo.certificateTypeNo']")
    private WebElement custCardNo;
    @FindBy(xpath = "//select[@ng-model='personnelInfo.certificateTypeCode']")
    private WebElement custCardType;
    @FindBy(xpath = "//button[contains(text(),'客户信息检索')]")
    private WebElement custSearchBtn;
    @FindBy(xpath = "//iframe[@id='doalogBox']")
    private WebElement custFrame;
    @FindBy(xpath = "//button[contains(text(),'确定客户信息')]")
    private WebElement confirmCustBtn;
    @FindBy(xpath = "//iframe[@name='dialogwin']")
    private WebElement quoteFrame;

    /*
    *车辆信息
    * */
    @FindBy(xpath = "//input[@ng-model='veh.vehicleLicenceCode']")
    private WebElement carLicence;
    @FindBy(xpath = "//input[@ng-model='veh.engineNo']")
    private WebElement engineNo;
    @FindBy(xpath = "//input[@id='vehicleFrameNo']")
    private WebElement vehicleFrameNo;
    @FindBy(xpath = "//input[@id='extBrand']")
    private WebElement carBrand;
    @FindBy(xpath = "//select[@id='autoModelCode']")
    private WebElement autoModelCode;
    @FindBy(xpath = "//input[@ng-model='veh.firstRegisterDate']")
    private WebElement registeDate;
    @FindBy(xpath = "//button[contains(text(),'交管车辆查询')]")
    private WebElement jgclQuery;
    @FindBy(xpath = "//button[contains(text(),'车型校验')]")
    private WebElement cxQuery;
    @FindBy(xpath = "//input[@type='button' and @value='确定']")
    private WebElement cxQueryConfirm;
    @FindBy(xpath = "//input[@ng-model='veh.verifyCode']")
    private WebElement jgclQueryCode;//教官车辆查询验证码输入框
    @FindBy(xpath = "//button[text()='提交']")
    private WebElement jgclCodeSubmit;
    @FindBy(xpath = "//div[@ng-if='ctrl.isCheckInput']/img")
    private WebElement imgCode;


    /*
    * 选择保障信息
    * */

    /*保险期限*/
    @FindBy(xpath = "//input[@ng-model='base.c51BaseInfo.insuranceBeginTime']")
    private WebElement forceBeginDate;
    @FindBy(xpath = "//input[@ng-model='base.c51BaseInfo.insuranceEndTime']")
    private WebElement forceEndDate;
    @FindBy(xpath = "//input[@ng-model='base.c01BaseInfo.insuranceBeginTime']")
    private WebElement commBeginDate;
    @FindBy(xpath = "//input[@ng-model='base.c01BaseInfo.insuranceEndTime']")
    private WebElement commEndDate;

    /*商业险*/
    @FindBy(xpath = "//input[@ng-model='ctrl.isCheckedComm' and @type='checkbox']")
    private WebElement commCheckbox;

    @FindBy(xpath = "//input[@type='checkbox' and contains(@ng-model,'dutys.0')]")
    private List<WebElement> riskList;

    @FindBy(xpath = "//tr[contains(@ng-style,'dutys.0')]")
    private List<WebElement> riskListNew;


    /*交强险*/
    @FindBy(xpath = "//input[@ng-model='ctrl.isCheckedForce' and @type='checkbox']")
    private WebElement forceCheckbox;
    @FindBy(xpath = "//span[@ng-bind='base.c51BaseInfo.totalActualPremium']")
    private WebElement forceFee;
    @FindBy(xpath = "//span[@ng-bind='vehicleTaxInfo.totalTaxMoney']")
    private WebElement forceTax;
    @FindBy(xpath = "//div[@id='taxType']/span/label")
    private List<WebElement> taxType;//交强险纳税类型
    @FindBy(xpath = "//select[@id='vehicleTaxInfo.deductionDueCode']")
    private WebElement reduceTaxReason;
    @FindBy(xpath = "//select[@id='vehicleTaxInfo.deductionDueType']")
    private WebElement reduceTaxType;
    @FindBy(xpath = "//input[@ng-model='vehicleTaxInfo.deductionDueProportion']")
    private WebElement reduceRate;
    @FindBy(xpath = "//input[@ng-model='vehicleTaxInfo.payTaxNo']")
    private WebElement taxNo;


    /*
    * 被保人信息
    * */
    @FindBy(xpath = "//input[@ng-model='personnelInfo.insureSameText']")
    private WebElement insured;
    @FindBy(xpath = "//div[@class='pui-dropdown-trigger ui-state-default ui-corner-right']/span")
    private WebElement insuredSelect;
    @FindBy(xpath = "//div[@class='pui-dropdown-items-wrapper']/ul/li")
    private List<WebElement> insuredList;
    @FindBy(xpath = "//input[@ng-model='personnelInfo.linkmodeNum']")
    private WebElement insuredMobile;

    /*
    * 申请报价
    * */
    @FindBy(xpath = "//button[contains(text(),'申请报价')]")
    private WebElement applyQuote;
    @FindBy(xpath = "//div[contains(@ng-repeat,'quoteFail.detailMsg')]")
    private List<WebElement> quoteResult;
    @FindBy(xpath = "//div[@class='ui_content']")
    private WebElement quoteSuccess;
    @FindBy(xpath = "//div[@id='loading']")
    private WebElement loading;

    public OrderPage(WebDriver driver, Action action) {
        super(driver, action);
        this.action = action;
        this.driver = driver;
        PageFactory.initElements(this.driver, this);
    }

    public void search(String no) throws Exception {
        action.inputText(this.cardNo, no);
        action.click(searchBtn);
        action.switchToWindowByUrl(searchResultUrl, false);
        action.pause(1000l);
    }

    public void searchCust(String name, String cardType, String cardNo) throws Exception {
        action.inputText(custName, name);
        if(StringUtils.isNotBlank(cardType)){
            action.select(this.cardType,cardType);//默认身份证
        }
        action.inputText(custCardNo, cardNo);
        action.click(custSearchBtn);
        action.pause(1000l);
        if(action.isAlertPresent()){
            action.acceptAlert();
            return;
        }
        action.switchToFrame(custFrame);
        action.pause(1000l);
        action.click(confirmCustBtn);
        driver.switchTo().defaultContent();
        driver.switchTo().frame("main");
    }

    public void fillCardInfo(String cLicenceNo, String engineNo, String vehicleNo, String brand, String brandInfo, String date) throws Exception {
        /*
        * 如果车架号不为空，则点击“车型校验”，如果校验不出则手工输入
        * */
        if (StringUtils.isNotBlank(vehicleNo)) {
            action.inputText(vehicleFrameNo, vehicleNo);
            action.click(cxQuery);
            if (driver.getPageSource().contains("未匹配到符合条件的车型，请手工录入！")) {
                action.click(cxQueryConfirm);
                action.inputText(carBrand, brand);
                action.pause(1000l);
                action.click(autoModelCode);
                action.pause(1000l);
                action.select(autoModelCode, brandInfo);
            }
        }
        /*填车牌号、发动机号*/
        if (StringUtils.isNotBlank(cLicenceNo)) {
            action.inputText(carLicence, cLicenceNo);
            /*如果输入车牌号，且为江苏车牌号，则击交管车辆查询*/
            if(cLicenceNo.startsWith("苏")){
                action.click(jgclQuery);
                action.pause(1000);
                /*交管车辆查询验证码截图*/
                /*String imageName = createElementImage(driver, imgCode);
                String valCode = new OCR().recognizeText(new File(imageName), "png");*/
                String valCode = "";
                if(StringUtils.isBlank(valCode)){
                    action.pause(8000l);
                    //人工输入验证码
                    action.click(jgclCodeSubmit);
                }
            }
        }
        if (StringUtils.isNotBlank(engineNo)) {
            action.inputText(this.engineNo, engineNo);
        }

        /*初登日期,如果使用“交管车辆查询”则会带出初登日期*/
        if(StringUtils.isBlank(registeDate.getAttribute(Constants.ATTR_VALUE))){
            action.inputText(registeDate, date);
        }
    }

    public void fillInsuredPeriod(String forceBegin,String forceEnd,String commBegin,String commEnd) throws Exception{
        if(StringUtils.isNotBlank(forceBegin)){
            action.inputText(forceBeginDate,forceBegin);
        }
        if(StringUtils.isNotBlank(forceEnd)){
            action.inputText(forceEndDate,forceEnd);
        }
        if(StringUtils.isNotBlank(commBegin)){
            action.inputText(commBeginDate,commBegin);
        }
        if(StringUtils.isNotBlank(commEnd)){
            action.inputText(commEndDate,commEnd);
        }

    }

    public void selectInsType(String[] insType, Map taxInfo, String[] riskNames) throws Exception {
        if (insType != null && insType.length > 0) {
            for (String s : insType) {
                if ("商业险".equals(s)) {
                    action.scrollTo(commCheckbox);
                    action.click(commCheckbox);
                    if (riskListNew != null && riskListNew.size() > 1) {
                        for (String risk : riskNames) {
                            for (WebElement row : riskListNew) {
                                WebElement riskEle = row.findElement(By.xpath("td[2]"));
                                if (risk.equals(riskEle.getText().trim())) {
                                    action.click(row.findElement(By.xpath("td[1]/input")));
                                    if("机动车第三者责任保险".equals(risk)){
                                        WebElement pcxeSelect = row.findElement(By.xpath("td[3]/table/tbody/tr[1]/td/select"));
                                        action.select(pcxeSelect,"100");
                                    }
                                    break;
                                }
                            }
                        }
                    }
                } else if ("交强险".equals(s)) {
//                    action.scrollTo(forceCheckbox);
                    action.click(forceCheckbox);
                    if(taxType!=null&&taxType.size()>0){
                        for(WebElement tax:taxType){
                            String tt = (String) taxInfo.get("taxtype");
                            if(tt.equals(tax.getText().trim())){
                                action.click(tax);
                                action.select(reduceTaxReason, (String) taxInfo.get("reducereason"));
                                String reduceType = (String) taxInfo.get("reducetype");
                                action.select(reduceTaxType,reduceType);
                                if("减税".equals(tt)){
                                    if("比例减免".equals(reduceType)){
                                        action.inputText(reduceRate, (String) taxInfo.get("reducerate"));
                                        action.inputText(taxNo, (String) taxInfo.get("taxno"));
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

    public void selectInsured(String mobile) throws Exception {
        action.scrollTo(insuredSelect);
        action.click(insuredSelect);
        if (insuredList != null && insuredList.size() > 1) {
            action.click(insuredList.get(1));
        }
        action.inputText(insuredMobile, mobile);
    }

    public void applyQuote() throws Exception {
        action.click(applyQuote);
        action.waitForPageLoad();
    }

    public String getQuoteResult() throws Exception {
        waitQuote();
        if (driver.getPageSource().contains("申请报价完成并保存报价单成功")) {
            return quoteSuccess.getText().trim();
        }
        action.switchToFrame(quoteFrame);
        StringBuffer sb = new StringBuffer();
        if (quoteResult != null && quoteResult.size() > 0) {
            for (WebElement e : quoteResult) {
                sb.append(e.getText().trim());
            }
        }
        return sb.toString();
    }

    public void waitQuote() throws Exception {
        WebDriverWait wait = new WebDriverWait(driver, ConfigPropInfo.DRIVER_EXPLICIT_WAIT);
        wait.until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver driver) {
                Boolean flag = false;
                try {
                    flag = driver.getPageSource().contains("申请报价完成并保存报价单成功");
                } catch (Exception e) {
                }
                return flag;
            }
        });
    }

    public static String createElementImage(WebDriver driver, WebElement webElement)
            throws IOException {
        // 获得webElement的位置和大小。
        Point location = webElement.getLocation();
        Dimension size = webElement.getSize();
        // 创建全屏截图。
        BufferedImage originalImage =
                ImageIO.read(new ByteArrayInputStream(takeScreenshot(driver)));

        // 截取webElement所在位置的子图。
        BufferedImage croppedImage = originalImage.getSubimage(
                location.getX() + 160,
                location.getY() + 42,
                size.getWidth(),
                size.getHeight());
        String fileName = ConfigPropInfo.TEST_SRCSHOT_DIR + "imgcode-" + System.currentTimeMillis() + ".png";
        ImageIO.write(croppedImage, "png", new File(fileName));
        return fileName;
    }

    public static byte[] takeScreenshot(WebDriver driver) throws IOException {
        /*WebDriver augmentedDriver = new Augmenter().augment(driver);
        return ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.BYTES);*/
        TakesScreenshot takesScreenshot = (TakesScreenshot) driver;
        return takesScreenshot.getScreenshotAs(OutputType.BYTES);
    }

    public static void snapshot2(WebDriver drivername, String filename) {
        // this method will take screen shot ,require two parameters ,one is driver name, another is file name


        //  File scrFile = drivername.getScreenshotAs(OutputType.FILE);
        // Now you can do whatever you need to do with it, for example copy somewhere
        try {
//            WebDriver augmentedDriver = new Augmenter().augment(drivername);
            File screenshot = ((TakesScreenshot) drivername).getScreenshotAs(OutputType.FILE);
            File file = new File("E:\\" + filename);
            FileUtils.copyFile(screenshot, file);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("Can't save screenshot");
            e.printStackTrace();
        } finally {
            System.out.println("screen shot finished");
        }
    }


}
